package edu.gduf.service.impl.infoentry;

import edu.gduf.dao.StudentClassDao;
import edu.gduf.domain.ResultInfo;
import edu.gduf.domain.StudentClass;
import edu.gduf.service.InfoEntryService;
import edu.gduf.utils.PoiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 谢佳豪
 * @data 2020/8/29 - 12:59
 * @target student_class表信息录入业务类
 */
@Service
public class StudentClassInfoEntryServiceImpl implements InfoEntryService {

    private StudentClassDao studentClassDao;

    @Autowired
    public void setStudentClassDao(StudentClassDao dao) {
        this.studentClassDao = dao;
    }

    @Override
    public ResultInfo informationEntry(String filepath) {
        //获取文件解析后返回的列表
        List<List<String>> lists = PoiUtil.readFile(filepath);

        //解析列表生成studentClass对象列表
        List<StudentClass> studentClassList = readList(lists);

        //判断是否存在重复主键
        List<String> allNums = studentClassDao.findAllNums();
        //声明重复主键列表
        List<String> repeatNumsList = new ArrayList<>();

        for (StudentClass studentClass : studentClassList){
            if (allNums.contains(studentClass.getClassNum())){
                //将重复主键添加到列表中
                repeatNumsList.add(studentClass.getClassNum());
            }
        }

        //判断重复主键列表是否为空
        if (repeatNumsList.size() > 0){
            return ResultInfo.failInfo("存在重复班级号,请进行检查！", repeatNumsList);
        }

        int i = studentClassDao.addStudentClassList(studentClassList);

        return ResultInfo.successInfo("成功录入" + i + "条数据");
    }

    private List<StudentClass> readList(List<List<String>> lists){
        List<StudentClass> studentClassList = new ArrayList<>();
        for (List<String> list : lists){
            StudentClass studentClass = new StudentClass();
            //设置studentClass对象的值
            studentClass.setClassNum(list.get(0));
            studentClass.setPartyMembers(Integer.valueOf(list.get(1)));
            studentClass.setClassMembers(Integer.valueOf(list.get(2)));

            //将对象数据添加进list中
            studentClassList.add(studentClass);
        }
        return studentClassList;
    }
}
